package com.base.themvx.adapter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.base.themvx.defNonSyncLazy

/**
 ******************(^_^)***********************<br>
 * Author: fee(QQ/WeiXin:1176610771)<br>
 * Time: 17:55<br>
 * <P>DESC:
 *  Fragment　数据集适配器
 * </p>
 * ******************(^_^)***********************
 */
class CommonFragmentsAdapter :
    FragmentStateAdapter {

    constructor(fragmentActivity: FragmentActivity
    ):super(fragmentActivity)

    constructor(fragmentManager: FragmentManager,life: Lifecycle): super(fragmentManager,life){

    }
    private val mFragments by defNonSyncLazy {
        mutableListOf<Fragment>()
    }

    /**
     * Returns the total number of items in the data set held by the adapter.
     *
     * @return The total number of items in this adapter.
     */
    override fun getItemCount(): Int {
        return mFragments.size
    }

    /**
     * Provide a new Fragment associated with the specified position.
     *
     *
     * The adapter will be responsible for the Fragment lifecycle:
     *
     *  * The Fragment will be used to display an item.
     *  * The Fragment will be destroyed when it gets too far from the viewport, and its state
     * will be saved. When the item is close to the viewport again, a new Fragment will be
     * requested, and a previously saved state will be used to initialize it.
     *
     * @see ViewPager2.setOffscreenPageLimit
     */
    override fun createFragment(position: Int): Fragment {
        return mFragments[position]
    }

    fun addFragment(fragment: Fragment?){
        if (fragment == null) {
            return
        }
        mFragments.add(fragment)
    }

//    fun addFragment(fragment: Fragment, position: Int) {
//        mFragments.add(position,fragment)
//        //对于本类型的Adapter　不支持在中间插入一个　Fragment
//        notifyItemInserted(position)
//    }

    fun addFragmentToTail(fragment: Fragment) {
        mFragments.add(fragment)
        notifyItemInserted(itemCount - 1)
    }

    fun clear(){
        mFragments.clear()
        notifyDataSetChanged()
    }

}